<?php

namespace Tests\Feature;

use App\Services\ElasticsearchService;
use App\Services\SearchIndexServiceInterface;
use Elastic\Elasticsearch\ClientBuilder;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;

class ElasticsearchServiceTest extends TestCase
{
    private SearchIndexServiceInterface $service;

    protected function setUp(): void
    {
        $client = ClientBuilder::create()
            ->setHosts(['localhost:9200'])
            ->build();

        $this->service = new ElasticsearchService($client);
    }

    public function testSearch()
    {
        Cache::shouldReceive('has')
            ->once()
            ->andReturn(false);

        Cache::shouldReceive('put')
            ->once()
            ->andReturnNull();

        $params = [
            'query' => [
                'multi_match' => [
                    'query' => 'moscow',
                    'fields' => ['code', 'country', 'cityName.ru', 'cityName.en'],
                    'fuzziness' => 'AUTO'
                ]
            ]
        ];

        $result = $this->service->search('airports', $params);
        $this->assertIsArray($result);

        foreach ($result as $item) {
            $this->assertArrayHasKey('_index', $item);
            $this->assertArrayHasKey('_id', $item);
            $this->assertArrayHasKey('_source', $item);
            $this->assertIsArray($item['_source']);
        }
    }
}
